package algorithm.kmp;

/**
 * 暴力匹配
 *
 * @author jack.wu
 * @version 1.0
 * @date 2020-04-06
 */
public class ViolenceMatch {
    public static void main(String[] args) {
        String str = "i like XX and you";
        String subStr = "you";
        int index = violenceMatch(str, subStr);
        System.out.println("index : " + index);
    }

    /**
     * 暴力匹配
     *
     * @param str    原字符串
     * @param subStr 需要查找的字串
     * @return 字串在原字符串中的索引
     */
    public static int violenceMatch(String str, String subStr) {
        char[] s1 = str.toCharArray();
        char[] s2 = subStr.toCharArray();
        int s1Len = s1.length;
        int s2Len = s2.length;

        // 匹配原字符串的索引
        int i = 0;
        // 匹配子串的索引
        int j = 0;

        while (i < s1Len && j < s2Len) {
            if (s1[i] == s2[j]) {
                // 匹配成功
                i++;
                j++;
            } else {
                // 没有匹配成功
                i = i - (j - 1);
                j = 0;
            }
        }

        if (j == s2Len) {
            // 字串匹配成功了
            return i - j;
        }
        return -1;


    }
}

